package com.gedeshidai.shumadevelop.service.impl;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gedeshidai.shumadevelop.common.BaseResponse;
import com.gedeshidai.shumadevelop.common.ErrorCode;
import com.gedeshidai.shumadevelop.common.ResultUtils;
import com.gedeshidai.shumadevelop.exception.BusinessException;
import com.gedeshidai.shumadevelop.common.ErrorCode;
import com.gedeshidai.shumadevelop.exception.BusinessException;
import com.gedeshidai.shumadevelop.mapper.ProductDetailMapper;

import com.gedeshidai.shumadevelop.mapper.ProductMapper;
import com.gedeshidai.shumadevelop.mapper.UserMapper;
import com.gedeshidai.shumadevelop.model.dto.product.ProductAddRequest;
import com.gedeshidai.shumadevelop.model.dto.product.ProductDetailUpdateRequest;
import com.gedeshidai.shumadevelop.model.dto.product.ProductAddRequest;
import com.gedeshidai.shumadevelop.model.entity.History;
import com.gedeshidai.shumadevelop.model.entity.History;
import com.gedeshidai.shumadevelop.model.entity.Product;
import com.gedeshidai.shumadevelop.model.entity.ProductDetail;
import com.gedeshidai.shumadevelop.model.entity.User;
import com.gedeshidai.shumadevelop.service.HistoryService;
import com.gedeshidai.shumadevelop.model.vo.ProductPreviewVO;
import com.gedeshidai.shumadevelop.model.vo.SelectDetailVO;
import com.gedeshidai.shumadevelop.model.vo.UserVO;
import com.gedeshidai.shumadevelop.model.entity.User;
import com.gedeshidai.shumadevelop.model.enums.HistoryStatusEnum;
import com.gedeshidai.shumadevelop.service.HistoryService;
import com.gedeshidai.shumadevelop.service.ProductDetailService;
import com.gedeshidai.shumadevelop.service.ProductService;
import com.gedeshidai.shumadevelop.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Romdon
 * @description 针对表【products_detail(商品详情信息表)】的数据库操作Service实现
 * @createDate 2024-06-17 08:28:14
 */
@Service
public class ProductDetailServiceImpl extends ServiceImpl<ProductDetailMapper, ProductDetail>
        implements ProductDetailService {
    @Resource
    private ProductDetailMapper detailMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductService productService;
    @Resource
    private HistoryService historyService;
    @Resource
    private UserService userService;


    @Transactional
    @Override
    public boolean saveProduct(ProductAddRequest productAddRequest, HttpServletRequest request) {

        // 判断非空
        if (ObjectUtils.isEmpty(productAddRequest.getProductName()) || ObjectUtils.isEmpty(productAddRequest.getInStock()) ||
                ObjectUtils.isEmpty(productAddRequest.getProductPicture()) || ObjectUtils.isEmpty(productAddRequest.getProductType()) || ObjectUtils.isEmpty(productAddRequest.getProductCategory()) ||
                ObjectUtils.isEmpty(productAddRequest.getProductSupplierName()) || ObjectUtils.isEmpty(productAddRequest.getProductSupplierPhone()) || ObjectUtils.isEmpty(productAddRequest.getServiceGuarantee()) ||
                ObjectUtils.isEmpty(productAddRequest.getProductPriceCategory()) || ObjectUtils.isEmpty(productAddRequest.getRaiType()) || ObjectUtils.isEmpty(productAddRequest.getExchangeRestrictions()) ||
                ObjectUtils.isEmpty(productAddRequest.getTimeOn()) || ObjectUtils.isEmpty(productAddRequest.getTimeOff())) {
            throw new BusinessException(ErrorCode.NOT_DATA_ERROR);
        }

        // 判断下线时间 大于 上线时间
        if (productAddRequest.getTimeOff().before(productAddRequest.getTimeOn()))
            throw new BusinessException(ErrorCode.TIME_ERROR);

        // 获取用户账号
        User loginUser = userService.getLoginUser(request);

        // 插入基本信息
        Product product = new Product();
        product.setUserProxy(JSONUtil.toJsonStr(productAddRequest.getUserProxy()));
        product.setRemainingStock(productAddRequest.getInStock());
        product.setUserId(loginUser.getUserId());
        BeanUtils.copyProperties(productAddRequest, product);
        productMapper.insert(product);

        // 获取基本信息id, 赋值给详情信息, 插入详情信息
        ProductDetail productDetail = new ProductDetail();
        productDetail.setProductId(product.getProductId());
        productDetail.setShowTime(productAddRequest.getTimeOn().toString() + productAddRequest.getTimeOff().toString());
        BeanUtils.copyProperties(productAddRequest, productDetail);
        detailMapper.insert(productDetail);

        // 插入商品操作历史表
        History history = new History();
        history.setProductId(product.getProductId());
        history.setStatus(1);
        history.setUserAccount(loginUser.getUserAccount()); //获取用户账户
        if (!historyService.save(history))
            throw new BusinessException(ErrorCode.OPERATION_ERROR);

        return true;
    }

    @Transactional
    @Override
    public boolean updateProduct(ProductDetailUpdateRequest updateRequest, User loginUser) {
        if (updateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long productId = updateRequest.getProductId();
        if (productId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Product productById = productService.getById(productId);
        if (productById == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = productById.getUserId();
        String userProxy = productById.getUserProxy();
        List<String> list =new ArrayList<>();
        if (!StringUtils.isAnyBlank(userProxy)){
            list = JSONUtil.toList(userProxy, String.class);
        }
        Long loginUserId = loginUser.getUserId();
        if (!userId.equals(loginUserId) && !list.contains(loginUser.getUserAccount())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        String productName = updateRequest.getProductName();
        Integer inStock = updateRequest.getInStock();
        Integer remainingStock = updateRequest.getRemainingStock();
        Date timeOn = updateRequest.getTimeOn();
        Date timeOff = updateRequest.getTimeOff();
        Integer raiType = updateRequest.getRaiType();
        //可以为空
        String description = updateRequest.getDescription();
        //可以为空
        String richText = updateRequest.getRichText();
        String productType = updateRequest.getProductType();
        String productCategory = updateRequest.getProductCategory();
        String serviceGuarantee = updateRequest.getServiceGuarantee();
        Integer exchangeRestrictions = updateRequest.getExchangeRestrictions();
        String showTime = updateRequest.getShowTime();
        String productPicture = updateRequest.getProductPicture();
        //可以为空
        String cityWhitelist = updateRequest.getCityWhitelist();
        //可以为空
        String cityBlacklist = updateRequest.getCityBlacklist();
        String productSupplierName = updateRequest.getProductSupplierName();
        String productSupplierPhone = updateRequest.getProductSupplierPhone();
        Long productPriceCategory = updateRequest.getProductPriceCategory();
        //可以为空
        Integer pointsPrice = updateRequest.getPointsPrice();
        //可以为空
        BigDecimal cashPrice = updateRequest.getCashPrice();
        //可以为空
        String remark = updateRequest.getRemark();

        if (StringUtils.isAnyBlank(productName, productType, productCategory,
                serviceGuarantee, showTime, productPicture, productSupplierName, productSupplierPhone)) {
            throw new BusinessException(ErrorCode.NOT_DATA_ERROR);
        }
        if (ObjectUtils.isEmpty(inStock) || ObjectUtils.isEmpty(remainingStock) || ObjectUtils.isEmpty(timeOn) ||
                ObjectUtils.isEmpty(timeOff) || ObjectUtils.isEmpty(raiType) || ObjectUtils.isEmpty(exchangeRestrictions) ||
                ObjectUtils.isEmpty(productPriceCategory)) {
            throw new BusinessException(ErrorCode.NOT_DATA_ERROR);
        }
        if (timeOn.after(timeOff)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上线时间和下线时间有问题");
        }
        Product product = new Product(productId, productName, inStock, remainingStock
                , timeOn, timeOff, userId, userProxy);
        ProductDetail detail = new ProductDetail(productId, productName, raiType, description, richText, productType, productCategory,
                serviceGuarantee, exchangeRestrictions, showTime, null, null, productPicture, cityWhitelist, cityBlacklist, productSupplierName,
                productSupplierPhone, productPriceCategory, pointsPrice, cashPrice, remark);
        boolean updateProduct = productService.updateById(product);
        boolean updateProductDetail = this.updateById(detail);
        History history = new History();
        history.setProductId(productId);
        history.setStatus(HistoryStatusEnum.UPDATE.getCode());
        history.setUserAccount(loginUser.getUserAccount());
        boolean save = historyService.save(history);
        if (!updateProductDetail || !updateProduct || !save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return true;
    }

    @Override
    public ProductPreviewVO getPreviewById(Long id) {
        ProductPreviewVO productPreviewVO = detailMapper.getPreviewById(id);
        if(productPreviewVO==null){
            throw  new BusinessException(ErrorCode.EXIST_PRODUCT_ERROR);
        }
        return productPreviewVO;
    }

}




